package com.xprime.mobileFramework.file;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import com.adobe.fre.FREContext;



public class FileDownLoadAsync extends AsyncTask<String, String, String> 
{
	
	public Context context = null;
	public FREContext eventDispatcher = null;
	
	 String fileName = "";
	 String fileUrl = "";
	 String filePath = "";
	 
     boolean isCanceled = false;
     private ProgressDialog loagindDialog; // Loading Dialog
     
     @Override
     protected void onPreExecute() {
         super.onPreExecute();
//         showDialog(DIALOG_DOWNLOAD_PROGRESS);
         
         if( context != null )
    	 {
    		 Toast.makeText( context, "파일 다운로드를 시작합니다." , 5000 ).show();
    	 }
         
         loagindDialog = ProgressDialog.show(context, "Download",
                 "Loading. Please wait...", true, false);
     }

     @Override
     protected String doInBackground(String... strData) {
         int count;
         URL url = null;
         InputStream input = null;
         OutputStream output = null;
         
         fileName = strData[0];
         fileUrl = strData[1];
         filePath = strData[2];
         
         try {
        	 url = new URL(fileUrl);

             URLConnection connection = url.openConnection();
             connection.connect();

             int lenghtOfFile = connection.getContentLength();
             input = new BufferedInputStream(url.openStream());
             
             File sdcardHome = Environment.getExternalStoragePublicDirectory(filePath);
             if(! sdcardHome.isDirectory()) {
                 sdcardHome.mkdirs();
             }
             
 		     File file = new File( sdcardHome, fileName);
             output = new FileOutputStream(file);

             byte data[] = new byte[1024];

             long total = 0;
             while ((count = input.read(data)) != -1) {
                 total += count;
                 output.write(data, 0, count);
                 publishProgress(""+(int)((total*100)/lenghtOfFile), "0");
             }
             // callback onProgressUpdate
             publishProgress("0", "0");
             
             output.flush();
         } catch (Exception e) {
             e.printStackTrace();
         } finally {
             try{ if( output != null ) output.close(); }catch(Exception ex){}
             try{ if( input != null ) input.close(); }catch(Exception ex){}
         }
         return null;
     }
     
     @Override
     protected void onCancelled()
     {
         isCanceled = true;
         Environment.getExternalStoragePublicDirectory(filePath+"/"+fileName).delete();
         if( context != null )
    	 {
    		 Toast.makeText( context, "다운이 취소되었습니다." , 5000 ).show();
    	 }
//         activity.finish();
         super.onCancelled();
     }

     // publishProgress(…) 메소드 호출의 callback
     @Override
     protected void onProgressUpdate(String... progress) {
    	 
    	 Log.i("downLoadProgress", progress[0]);
     }

     
     @Override
     protected void onPostExecute(String unused) {
         //dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
//         checkFinishDown();
    	 
    	 if( context != null )
    	 {
    		 Toast.makeText( context, "다운이 완료되었습니다." , 5000 ).show();
    		 if( eventDispatcher != null )
 		    {
 		    	eventDispatcher.dispatchStatusEventAsync("fileDownLoadExtension", fileName );
 		    }
    	 }
    	 
    	  loagindDialog.dismiss(); // 다이얼로그 삭제
     }
}
